import React from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { Layout, Menu } from 'antd';
import type { MenuProps } from 'antd';
import {
  BankOutlined,
  CloudSyncOutlined,
  UserOutlined
} from '@ant-design/icons';
import { useStore, observer } from '../store/currentUser/storeHook';

const { Sider } = Layout;

type MenuItem = Required<MenuProps>['items'][number];

function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[],
  type?: 'group'
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
    type
  } as MenuItem;
}

const SiderLayout: React.FC<{ onPathnameChange?: (pathname: string) => void }> = ({ onPathnameChange }) => {
  const store: any = useStore();

  const location = useLocation();
  const navigate = useNavigate();

  const items: MenuProps['items'] = store.currentUser.hasRole('admin') ? [
    getItem('公司', 'company_menu', <BankOutlined />, [
      getItem('城市列表', 'city_list'),
      getItem('公司列表', 'company_list')
    ]),
    getItem('组织架构同步', 'sync_menu', <CloudSyncOutlined />, [
      getItem('同步任务', 'task_list')
    ]),
    getItem('用户', 'user_menu', <UserOutlined />, [
      getItem('用户管理', 'user_management'),
      getItem('登录日志', 'login_log_list'),
      getItem('验证码', 'verification_code_list')
    ])
  ] : (
    store.currentUser.hasRole('authorized') ? [
      getItem('公司', 'company_menu', <BankOutlined />, [
        getItem('公司列表', 'company_list')
      ]),
      getItem('组织架构同步', 'sync_menu', <CloudSyncOutlined />, [
        getItem('同步凭证', 'certificate_list'),
        getItem('同步任务', 'task_list')
      ])
    ] : []
  );

  const showPage = (key: string) => {
    const pathname: string = '/' + key;
    navigate(pathname);
    if (onPathnameChange != null) {
      onPathnameChange(pathname);
    }
  };

  const openKeys: string[] = [];
  const selectedKeys: string[] = [];
  const key: string = location.pathname.split('/')[1] || '';
  let openKey: string = '';
  let selectedKey: string = '';
  items.forEach(value => {
    ((value as any).children as Array<any>).forEach(v => {
      if (key === v.key) {
        openKey = value?.key as string;
        selectedKey = v?.key as string;
      }
    })
  });
  if (openKey) openKeys.push(openKey);
  if (selectedKey) selectedKeys.push(selectedKey);

  return (
    <Sider style={{ overflow: 'auto' }}>
      <Menu
        mode="inline"
        items={items}
        defaultOpenKeys={openKeys}
        selectedKeys={selectedKeys}
        style={{ height: '100%', borderRight: 0 }}
        onClick={e => showPage(e.key)}
      />
    </Sider>
  );
};

export default observer(SiderLayout);
